from rest_framework import serializers

from books.models import BookInfo


class HerosSerializer(serializers.Serializer):
    hname = serializers.CharField()
    hcomment = serializers.CharField()
    # hbook = serializers.PrimaryKeyRelatedField()
    # hbook = serializers.StringRelatedField()
    # 应该是会出问题
    # hbook = BooksSerializer(many=True)


class BooksSerializer(serializers.Serializer):
    btitle = serializers.CharField(max_length=20)
    bpub_date = serializers.DateField()
    bread = serializers.IntegerField(default=0)
    bcomment = serializers.IntegerField(default=5, min_value=3)
    # 返回关联的所有ｉｄ
    # heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    # 返回__str__返回的值
    # heroinfo_set = serializers.StringRelatedField(read_only=True, many=True)
    # heroinfo_set = HerosSerializer(read_only=True, many=True)

    # 单一字段进行验证
    def validate_btitle(self, value):
        if value == 'python':
            raise serializers.ValidationError('bu shi python')
        return value
    def validate(self, attrs):
        if attrs['btitle'] == attrs['bcomment']:
            raise serializers.ValidationError('cuo wu')
        return attrs


    def create(self, validated_data):
        book = BooksSerializer.objects.create(**validated_data)
        return book
    def update(self, instance, validated_data):
        instance.bread = validated_data['bread']
        instance.save()
        return instance


class BookSerializer(serializers.ModelSerializer):
    '''模型类创建'''
    # 直接自定义
    # bpub_date = serializers.DateField()

    class Meta:
        model = BookInfo
        # fields = ('btitle',)
        fields = '__all__'
        # exclude = ('btitle',)  取反创建反序列化验证
        # read_only_fields = ('bpub_date',) 自定义一个字段验证read_only=True
        # 添加或修改　　与讲义上的不同
        # extra_kwargs = {
        #     'bcomment':{
        #         'read':True
        #     }
        # }